"""
    log_control.py：日志打印封装,可设置颜色
"""
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2023/5/19
# @Author : Renee

import time
import logging
import colorlog
from logging import handlers
from typing import Text
from commons.get_path import ensure_path_sep


class LogHandler:
    # 日志级别关系映射
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    @classmethod
    def log_color(cls):
        """ 设置日志颜色 """
        log_colors_config = {
            'DEBUG': 'blue',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            # 'CRITICAL': 'red',
        }

        formatter = colorlog.ColoredFormatter(
            '%(log_color)s[%(asctime)s][%(levelname)s]: %(message)s',
            log_colors=log_colors_config
        )
        return formatter

    def __init__(
            self,
            filename: Text,  # 调用日志输出函数的文件名
            level: Text = "info",  # 输出的日志级别
            when: Text = "D",  # Days
            fmt: Text = "%(levelname)-8s:%(asctime)s %(name)s %(filename)s[line:%(lineno)d] %(message)s",  # 日期格式
    ):
        """
        levelname:报错级别
        asctime:日期
        name:路径
        filename:调用日志输出函数的文件名
        lineno:打印日志的当前行号
        message:报错内容
        """""

        """日志文件输出"""
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)  # 设置日志格式
        self.logger.setLevel(self.level_relations.get(level))  # 设置日志级别

        # 往文件里写入指定间隔时间自动生成文件的处理器
        time_rotating = handlers.TimedRotatingFileHandler(
            filename=filename,
            when=when,
            # interval, #等待多少个单位when的时间后，Logger自动重建文件
            backupCount=10,  # 保留10个日志
            encoding='utf-8'
        )

        # 设置日志文件里写入的格式
        time_rotating.setFormatter(format_str)

        """屏幕输出"""
        formatter = self.log_color()
        screen_output = logging.StreamHandler()

        screen_output.setFormatter(formatter)  # 设置屏幕显示的格式
        screen_output.setLevel(self.level_relations.get(level))  # 设置屏幕显示的级别

        # 把对象加到logger里
        self.logger.addHandler(screen_output)
        self.logger.addHandler(time_rotating)
        self.log_path = ensure_path_sep('\\logs\\log.log')  # 自定义日志路径


now_time_day = time.strftime("%Y-%m-%d", time.localtime())
# DEBUG = LogHandler(ensure_path_sep(f"\\logs\\info-{now_time_day}.log"), level='info')
INFO = LogHandler(ensure_path_sep(f"\\logs\\info-{now_time_day}.log"), level='info')
WARNING = LogHandler(ensure_path_sep(f'\\logs\\warning-{now_time_day}.log'), level='warning')
ERROR = LogHandler(ensure_path_sep(f"\\logs\\error-{now_time_day}.log"), level='error')




# if __name__ == '__main__':
#     ERROR.logger.error("This is error message")
#     INFO.logger.info("This is info message")
#     WARNING.logger.warning("This is warning message")